package tcp.ssl.pem.ssl;

import static sun.security.x509.CertificateAlgorithmId.ALGORITHM;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.security.KeyStore;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

/***
 * 参考：
 * http://iiaf.iteye.com/blog/466369
 */
public class ClientSSLTest {

  static String keystorePath = "/Users/dingjianfeng/IdeaProjects/GitTest/src/main/java/tcp/ssl/pem/ssl/mycerts";
  static String keystorePassword = "client";

  public static void main(String args[]) throws Exception {
    // System.setProperty("javax.net.debug", "ssl,handshake");
    /***
     * 默认算法
     */
    String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    /***
     * 默认的keystore
     */
    KeyStore ks = KeyStore.getInstance("JKS");
    /***
     * 加载证书
     */
    ks.load(new FileInputStream(keystorePath), keystorePassword.toCharArray());
    /***
     * 获取默认的key工厂
     */
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);

    kmf.init(ks, keystorePassword.toCharArray());
    /***
     * 受信任的key管理工厂
     */
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
    tmf.init(ks);
    SSLContext sslc = SSLContext.getInstance("TLS");
    sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

// The process is different from here on the client. Instead of
// getting a ServerSocketFactory, we ask for a SocketFactory from
// the SSL context.
    SocketFactory sf = sslc.getSocketFactory();

// Then we get the socket from the factory and treat it
// as if it were a standard (plain) socket.
    Socket sslsocket = sf.createSocket("192.168.10.6", 10000);

    System.out.println("Client Connected");
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(sslsocket.getOutputStream(), "UTF-8"));

    out.write("This is message from client！" + "\n");
    out.flush();
    System.out.println("Msg Sent");
    sslsocket.close();
  }
}
